package com.yupi.springbootinit.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class mqInitMain {
    private final static String QUEUE_NAME = "hello";
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建一个消息队列的对象工厂
        ConnectionFactory factory = new ConnectionFactory();
        //指定连接主机名
        factory.setHost("localhost");
        //创建一个新的连接
        Connection connection = factory.newConnection();
        //指定一个频道
        Channel channel = connection.createChannel();
        //声明一个消息队列，我们监听的是哪个消息队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        //DeliverCallback：接口中定义了如何处理消息的回调函数，delivery接收的消息
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        };
        //会在这个频道中消费消息，接收到的消息会传递给deliverCallback来处理，会持续阻塞
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
    }
}
